import axios from 'axios';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:9095';

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
});

// Request interceptor for logging
api.interceptors.request.use(
  (config) => {
    console.log(`[API] ${config.method?.toUpperCase()} ${config.url}`);
    return config;
  },
  (error) => {
    console.error('[API] Request error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor for error handling
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    console.error('[API] Response error:', error);
    return Promise.reject(error);
  }
);

export const apiService = {
  // Get all trodes
  getTrodes: async () => {
    const response = await api.get('/api/trodes');
    return response.data;
  },

  // Get trode list (configuration)
  getTrodeList: async () => {
    const response = await api.get('/api/trodes/list');
    return response.data;
  },

  // Get individual trode update
  getTrodeUpdate: async (trodeId) => {
    const response = await api.get(`/api/trodes/update?id=${trodeId}`);
    return response.data;
  },

  // Get chart data
  getCharts: async (timeRange = 'hour', historical = false) => {
    const params = new URLSearchParams();
    if (timeRange === 'day') {
      params.append('range', 'day');
    }
    if (historical) {
      params.append('historical', 'true');
    }
    
    const response = await api.get(`/api/charts?${params.toString()}`);
    return response.data;
  },

  // Get processes data
  getProcesses: async () => {
    const response = await api.get('/api/processes');
    return response.data;
  },

  // Get users data
  getUsers: async () => {
    const response = await api.get('/api/users');
    return response.data;
  },

  // Get dashboard data (for backward compatibility)
  getDashboard: async () => {
    const response = await api.get('/api/dashboard');
    return response.data;
  },

  // Node management methods
  getNodes: async () => {
    const response = await api.get('/api/nodes');
    return response.data;
  },

  getNode: async (id) => {
    const response = await api.get(`/api/nodes/${id}`);
    return response.data;
  },

  createNode: async (nodeData) => {
    const response = await api.post('/api/nodes', nodeData);
    return response.data;
  },

  updateNode: async (id, nodeData) => {
    const response = await api.put(`/api/nodes/${id}`, nodeData);
    return response.data;
  },

  deleteNode: async (id) => {
    const response = await api.delete(`/api/nodes/${id}`);
    return response.data;
  },

  validateNode: async (nodeData) => {
    const response = await api.post('/api/nodes/validate', nodeData);
    return response.data;
  },
};

export default apiService; 